package com.liang.book.service;

import com.liang.book.mapper.UserMapper;
import com.liang.book.model.Roles;
import com.liang.book.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public UserInfo queryUserByName(String userName){
        return userMapper.queryUserByName(userName);
    }

        @Transactional
        public boolean registerUser(UserInfo newUser) {
            System.out.println("newUser2: "+newUser);
            // 检查用户名是否已存在
            UserInfo existingUser = userMapper.findByUserName(newUser.getUserName());
            System.out.println("existingUser :" +existingUser );

            if (existingUser != null) {
                // 用户名已存在，注册失败
                return false;
            }
            System.out.println("KKK");
            // 保存新用户到数据库
            try {
                userMapper.save(newUser);
                System.out.println("aaa");
                System.out.println("newUser.getRole()"+newUser.getRole());
                if(newUser.getRole().equals("user")) {
                    userMapper.insertUserInfo(newUser);
                }
                System.out.println("bbb");
                if(newUser.getRole().equals("admin")){
                    userMapper.insertadmininfo(newUser);
                }
                System.out.println("ccc");
                // 注册成功
                return true;
            } catch (Exception e) {
                System.out.println("registerUser.serv ice fail");
                return false;
            }
        }

    public Roles findRole(String userName) {
        return userMapper.findRole(userName);
    }

    public UserInfo selectAdminInfo(String userName) {
        return userMapper.selectAdminInfo(userName);
    }
}
